/*
@Time : 2022/5/27 17:17
@Author : gaozhichang
@File : gorm.go
@des: GoLand
*/
package main

import (
	"fmt"
	"gorm.io/gorm"
	//"database/sql/driver"
	"gorm.io/driver/mysql"
)

/**
CREATE TABLE `t1` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `t1` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0正常，1删除',
  `t2` tinyint(4) NOT NULL DEFAULT '0' COMMENT ' ',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

+-------+---------------------+------+-----+---------+----------------+
| Field | Type                | Null | Key | Default | Extra          |
+-------+---------------------+------+-----+---------+----------------+
| id    | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| t1    | tinyint(1)          | NO   |     | 0       |                |
| t2    | tinyint(4)          | NO   |     | 0       |                |
+-------+---------------------+------+-----+---------+----------------+

 */

type T1 struct {
	Id int64 `gorm:"id" json:"name"`
	T1 int   `gorm:"column:t1" json:"t1"`
	T2 int   `gorm:"column:t2" json:"t2"`
}

//设置表名，默认是结构体的名的复数形式
func (T1) TableName() string {
	return "t1"
}

func main() {
	dsn := "%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=UTC"

	dsn = fmt.Sprintf(
		dsn,
		"root",
		"123456",
		"127.0.0.1",
		3306,
		"test",
	)
	fmt.Println(dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		PrepareStmt:                              false,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		fmt.Println("connect db err: ", err)
	}
	//defer db.Close()

	t1 := &T1{}
	id := 2

	//当不存在是 find 不回返回 record not found
	err = db.Model(t1).Find(t1, "id = ?", int64(id)).Error
	fmt.Println(err)
	fmt.Println(t1)

	err = db.Model(t1).Take(t1, "id = ?", int64(id)).Error
	fmt.Println(err)
	fmt.Println(t1)

	fmt.Println(gorm.ErrRecordNotFound)
}
